package com.thornbird.vehiclerecycling.controller;

import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.thornbird.vehiclerecycling.annotation.CurrentUser;
import com.thornbird.vehiclerecycling.exception.NotFoundException;
import com.thornbird.vehiclerecycling.model.record.OrderRecord;
import com.thornbird.vehiclerecycling.model.record.UserRecord;
import com.thornbird.vehiclerecycling.service.OrderService;
import com.thornbird.vehiclerecycling.util.EncryptUtil;
import com.thornbird.vehiclerecycling.util.PdfUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@Configuration
public class IndexController {

    @Value("${app.image-path}")
    private String imagePath;

    @Value("${app.report.backgrounds}")
    private String backgrounds;

    @Value("${app.report.authority-signature}")
    private String authoritySignature;

    private final OrderService orderService;

    @Autowired
    public IndexController(OrderService orderService) {
        this.orderService = orderService;
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/", "/page/order"})
    public String order(HttpServletRequest request) {
        request.getSession().setAttribute("page", "order");
        return "order";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/page/user")
    public String user(HttpServletRequest request, @CurrentUser UserRecord userRecord) {
        if (userRecord.getSuperUser() == null || !userRecord.getSuperUser()) {
            return "error/403";
        }
        request.getSession().setAttribute("page", "user");
        return "user";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/page/config")
    public String config(HttpServletRequest request, @CurrentUser UserRecord userRecord) {
        if (userRecord.getSuperUser() == null || !userRecord.getSuperUser()) {
            return "error/403";
        }
        request.getSession().setAttribute("page", "config");
        return "config";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/page/public/check/{id}/{checkNumber}")
    public ModelAndView check(@PathVariable Long id, @PathVariable Integer checkNumber) {
        ModelAndView modelAndView = new ModelAndView("check");
        boolean valid = false;
        OrderRecord orderRecord = null;
        try {
            orderRecord = orderService.findOrder(id);
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        if (orderRecord != null && orderRecord.getCheckCode() != null
                && EncryptUtil.md52int(orderRecord.getCheckCode()) == checkNumber.intValue()) {
            valid = true;
        }
        if (!valid) {
            orderRecord = new OrderRecord();
            orderRecord.setId(0L);
        }
        modelAndView.getModel().put("order", orderRecord);
        return modelAndView;
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/page/pdf/recyclingCertificate/{id}/{index}/{shading}"})
    public void recyclingCertificate(@PathVariable(value = "id") Long id,
                                     @PathVariable(value = "index") Integer index,
                                     @PathVariable(value = "shading") Boolean shading,
                                     HttpServletResponse response)
            throws NotFoundException, IOException {
        if (index == null || index < 0 || index > 6) {
            throw new NotFoundException();
        }

        OrderRecord orderRecord = orderService.findOrder(id);
        List<String> backgroundImages = Arrays.asList(backgrounds.split(","))
                .stream().map(x -> imagePath + x).collect(Collectors.toList());
        if (shading) {
            if (index > 0) {
                String backgroundImage = backgroundImages.get((index - 1) % backgroundImages.size());
                backgroundImages = new ArrayList<>();
                backgroundImages.add(backgroundImage);
            }
        } else {
            backgroundImages = null;
        }

        PdfWriter pdfWriter = PdfUtil.createPdfWriter(response, "报废机动车回收证明.pdf");
        Document document = PdfUtil.createDocument(pdfWriter, true, backgroundImages);
        if (index == 0) {
            for (int i = 0; i < 6; i++) {
                PdfUtil.createRecyclingCertificate(document, orderRecord, imagePath + authoritySignature, i + 1, i > 0);
            }
        } else {
            PdfUtil.createRecyclingCertificate(document, orderRecord, imagePath + authoritySignature, index, false);
        }
        PdfUtil.saveDocument(document, pdfWriter);
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/page/pdf/cancellationCertificate/{id}"})
    public void cancellationCertificate(@PathVariable(value = "id") Long id, HttpServletResponse response)
            throws NotFoundException, IOException {
        OrderRecord orderRecord = orderService.findOrder(id);
        PdfWriter pdfWriter = PdfUtil.createPdfWriter(response, "机动车注销证明书.pdf");
        Document document = PdfUtil.createDocument(pdfWriter);
        PdfUtil.createCancellationCertificate(document, orderRecord);
        PdfUtil.saveDocument(document, pdfWriter);
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/page/pdf/cancellationCertificate2/{id}"})
    public void cancellationCertificate2(@PathVariable(value = "id") Long id, HttpServletResponse response)
            throws NotFoundException, IOException {
        OrderRecord orderRecord = orderService.findOrder(id);
        PdfWriter pdfWriter = PdfUtil.createPdfWriter(response, "机动车注销证明书.pdf");
        Document document = PdfUtil.createDocument(pdfWriter);
        PdfUtil.createCancellationCertificate2(document, orderRecord);
        PdfUtil.saveDocument(document, pdfWriter);
    }

}
